package com.lmf.case1;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * 实现多台服务器在zookeeper上面注册，并在多个客户端监听并连接服务器的案例：
 * 1.服务器注册zk
 */
public class DistributeServer {
    private String connectString = "192.168.120.128:2181,192.168.120.130:2181,192.168.120.131:2181";
    private int sessionTimeOut = 200000;
    private ZooKeeper zooKeeper;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DistributeServer server = new DistributeServer();
        //连接zk
        server.connect();
        //注册zk
        server.regist(args[0]);
        //等待开展业务逻辑（保持线程睡眠状态）
        server.business();
    }

    private void business() throws InterruptedException {
        //睡眠等待客户端访问
        Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String hostname) throws InterruptedException, KeeperException {
        //注册zk，就是在zk里面创建一个节点，即告诉外界本台服务器已经上线了，可以来访问我了
        zooKeeper.create("/servers/"+hostname,hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname +" is online") ;
    }

    private void connect() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeOut, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}
